package com.pangu.security;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.ioc.Ioc;
import org.nutz.log.Log;
import org.nutz.log.Logs;

public class SecurityFilter implements Filter {
	private static final Log logger = Logs.getLog(SecurityFilter.class);

	protected AuthService authService;
	protected SecurityContextHolder securityContextHolder;

	public void destroy() {
		securityContextHolder.clear();
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		long start = System.currentTimeMillis();
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		try {
			if (authService.validate(req) < 0)
				throw new AuthException("");
			chain.doFilter(request, response);
		} catch (AuthException e) {
			res.sendRedirect(req.getContextPath() + "/login?t="
					+ URLEncoder.encode(req.getRequestURI(), "UTF-8"));
		} finally {
			long stay = System.currentTimeMillis() - start;
			if (logger.isInfoEnabled()) {
				SessionInfo sessionInfo = securityContextHolder
						.getSessionInfo();
				String userInfo = sessionInfo == null ? "" : sessionInfo
						.getUserId() + "," + sessionInfo.getUserName() + " ";
				logger.info(req.getRequestURI() + ": " + userInfo + stay);
			}
			securityContextHolder.clear();
		}
	}

	public void init(FilterConfig config) throws ServletException {
		ServletContext servletContext = config.getServletContext();
		Ioc ioc = (Ioc) servletContext.getAttribute(Ioc.class.getName());
		authService = (AuthService) ioc.get(AuthService.class, "authService");
		securityContextHolder = (SecurityContextHolder) ioc.get(
				SecurityContextHolder.class, "securityContextHolder");
	}

}
